import { useState, useEffect, useMemo, useRef } from 'react';
import { Input, Modal, Table, notification } from 'antd';
import { searchData } from './search-data';
import { emPage } from './rq';
import { CommonModelProps, } from '@/components/schema-form-render/meta';
import { SchemaFormSearchContent } from '@/components/schema-form-render/components/schema-form-content';
import { initialSchemaSearch } from "@/components/schema-form-render/utils";
import { ExtBtn } from '@/components/SelfIcon';
import { useScemaRender } from '../hoc-form/utils';
import { setDeptParams } from './hooks';
import _ from 'lodash';
import { onFormMount } from '@formily/core';
import { toJS } from '@formily/reactive'
import { getValidateMessage } from '@/utils/validate-rules/message';
export interface SingleEpModalProps extends CommonModelProps {
  companyCode: string;
  deptCode: string;
  onChange: (e: string, data: any) => any;
  value: string | undefined | any;
  noDept?: boolean;
  disabled?: boolean;
}
// 弹窗 hooks
export const useModal = (): any => {
  const [visible, setVisible] = useState<boolean>(false);
  const [fg, setfg] = useState(false);

  const hideModel = () => {
    setVisible(false);
    setfg(!fg)
  };
  const showModel = () => {
    setVisible(true);
  };
  return [visible, hideModel, showModel, setfg, fg];
};

const SingleEpModal = (props: SingleEpModalProps): any => {
  const { companyCode, onChange, value, deptCode, disabled } = props;
  const propsRef = useRef(props);
  useEffect(() => {
    propsRef.current = props;
  }, [props])
  const pageSize = 5;
  // const [metas, setMetas] = useState<Meta[]>();
  const [configs, setConfigs] = useState<any>(null);

  const [pageNo, setPageNo] = useState<number>(1);
  const [current, setCurrent] = useState<number>(0);
  const [total, setTotal] = useState<number>(0);
  const [dvalue, setDvalue] = useState<any>('');
  const [cvalue, setCvalue] = useState<any>('');
  const [loading, setLoading] = useState<boolean | any>(false);
  const [data, setData] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  // 弹窗
  const [visible, hideModel, showModel, setfg, fg] = useModal();
  const cols = [
    {
      title: getValidateMessage('config.common.label.code', true),
      dataIndex: 'code',
    },
    {
      title: getValidateMessage('single-ep-modal.Employ Name', true),
      dataIndex: 'name',
    },
    {
      title: getValidateMessage('single-ep-modal.Parent Name', true),
      dataIndex: 'parentName',
    },
  ];

  const { form, SchemaFormRender } = useScemaRender({}, {
    effects() {
      onFormMount((form) => {
        console.log('form初始化', propsRef?.current)
        setDeptParams(form, {
          parentCode: propsRef?.current?.companyCode
        }, {
          deptCode: propsRef?.current?.deptCode,
          code: propsRef?.current?.value
        });
      })
    }
  }, false, false, [fg]);

  useEffect(() => {
    setConfigs(initialSchemaSearch(
      searchData
    ))
  }, [])
  // 获取分页数据
  const getPageData = async (params: any = {}, pn?: number, cb?: any) => {
    if (loading) return;
    setLoading(true);
    try {
      const res: any = await emPage({
        pageNo: pn || pageNo,
        pageSize,
        type: 'EMPLOYEE',
        queryKeys: {
          "pageCode": "ORGMAINT_L",
        },
        companyCode,
        deptCode,
        code: value,
        "recursion": true,
        ...params,
      });
      if (res.success) {
        // 分页信息 以及 选择项目处理
        // setSelectedRowKeys([]);
        const data = res.result.content.map((i: any) => ({
          ...i,
          id: i._id
        }))
        setData(data);
        setPageNo(pageNo + 1);
        setTotal(res.result.total);
        setCurrent(res.result.pageNo + 1);
        if (cb) {
          cb(data);
        }
      }
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };
  // const getPageData = useMemo(() => {
  //   return _.throttle(__getPageData, 500)
  // }, [])
  // 处理表单数据查询
  const handleSearch = (pn = 1): any => {
    const params = toJS(form.values)
    return getPageData(params, pn);
  };
  // 控制保存数据同步更新 id 和 name
  const saveData = (id: string, cb?: any, dt?: any[], noTrigger: boolean = false) => {
    const opData = dt || data;
    const res = opData.find(item => item.id === id);
    setDvalue(res.name);
    setCvalue(res.code);
    if (!noTrigger) {
      onChange(res.code, res);
    }
    if (cb) cb();
  };

  // 对所有数据进行初始化
  const clearModelData = (cb?: any) => {
    setDvalue('');
    setCvalue('');
    setSelectedRowKeys([]);

    if (cb) cb();
  };

  useEffect(() => {
    // 还未进行初始化
    // 清空操作
    if (dvalue && !value) {
      clearModelData(() => { });
    } else if ((value && !dvalue) || value !== cvalue) {
      // 通过初始化设置值
      const obj = {
        deptCode,
        code: value,
        companyCode,
      };
      // 初始化各类数据
      getPageData(obj, 1, (dt: any[]) => {
        const res = dt && dt.length ? dt.find(item => item.code === value) : null;
        saveData(
          res && res.id,
          () => {
            setDeptParams(form, {
              parentCode: companyCode
            }, { deptCode, code: value })
          },
          dt,
          true,
        );
        setSelectedRowKeys(res ? [res.id] : []);
      });
    }
    // return clearModelData(); companyCode
  }, [value]);

  useEffect(() => {
    if (companyCode || deptCode) {
      setDeptParams(form, {
        parentCode: companyCode
      }, { deptCode })
      getPageData({}, 1);
    }
  }, [companyCode, deptCode]);
  return (
    <>
      <Input
        onClick={() => {
          if (!companyCode) {
            return notification.error({
              message: getValidateMessage('single-ep-modal.Please select [Company] before !', true),
            });
          }

          showModel();
        }}
        disabled={disabled}
        value={dvalue}
      />
      <Modal
        width={900}
        // destroyOnClose
        visible={visible}
        title={getValidateMessage('single-ep-modal.Select Employ', true)}
        onOk={() => {
          if (selectedRowKeys && selectedRowKeys.length > 0) {
            saveData(selectedRowKeys[0], hideModel);

          }
        }}
        onCancel={() => {
          hideModel();
        }}
      >
        <SchemaFormSearchContent footer={[
          <ExtBtn
            loading={loading}
            style={{ marginRight: 10 }}
            onClick={() => {
              setPageNo(1);
              handleSearch(1);
            }}
            type="primary"
            icon="chaxun"
            name={getValidateMessage('common.search', true)}
          />,
          <ExtBtn
            loading={loading}
            style={{ marginRight: 10 }}
            onClick={() => {
              form.reset()
            }}
            type="primary"
            icon="chongzhi"
            name={getValidateMessage('common.reset', true)}
          />
        ]}>
          <SchemaFormRender schema={configs?.schema} pageConfig={configs?.pageConfig} />
        </SchemaFormSearchContent>
        <Table
          size="small"
          rowKey="id"
          dataSource={data}
          columns={cols}
          rowSelection={{
            type: 'radio',
            selectedRowKeys,
            onChange: (sr: any[]) => setSelectedRowKeys(sr),
          }}
          pagination={{
            pageSize,
            current,
            onChange: pn => handleSearch(pn),
            total,
          }}
        />
      </Modal>
    </>
  );
};

export default SingleEpModal;
